//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet.Data
{
    internal class ComplexConnection: DataConnection
    {
        public ComplexConnection(DataConnection connection1, DataConnection connection2)
        {
            Contract.Requires(connection1 != null);
            Contract.Requires(connection2 != null);
            foreach (var c in getConnections(connection1))
            {
                _textConnection = SafeCast<TextConnection>(c);
                _databaseConnection = SafeCast<DatabaseConnection>(c);
                _olapConnection = SafeCast<OlapConnection>(c);
                webQueryConnection = SafeCast<WebQueryConnection>(c);

            }
            foreach (var c in getConnections(connection2))
            {
                _textConnection = SafeCast<TextConnection>(c);
                _databaseConnection = SafeCast<DatabaseConnection>(c);
                _olapConnection = SafeCast<OlapConnection>(c);
                webQueryConnection = SafeCast<WebQueryConnection>(c);
            }
            Contract.Assert(Enumerable.Count<DataConnection>(getConnections(this)) >= 2);
        }

        static IEnumerable<DataConnection> getConnections (DataConnection connection)
        {
            if (connection is ComplexConnection)
            {
                var complexConnection = (ComplexConnection) connection;
                yield return complexConnection.webQueryConnection;
                yield return complexConnection._databaseConnection;
                yield return complexConnection._olapConnection;
                yield return complexConnection._textConnection;
            }
            else
            {
                yield return connection;
            }
        }

        private T SafeCast<T>(DataConnection connection)where T: class
        {
            if (connection is T)
                return (T)(object) connection;
            return null;
        }

        private TextConnection _textConnection;
        private DatabaseConnection _databaseConnection;
        private OlapConnection _olapConnection;
        private WebQueryConnection webQueryConnection;

        internal override void Initialize()
        {
            
        }

        internal override void ReadProperties(ReadContext context)
        {
            
        }

        internal override void WriteProperties(WriteContext context)
        {
            foreach (var enumerable in Enumerable.Where(getConnections(this), cc => cc != null))
            {
                enumerable.WriteProperties(context);
            }
            
        }

        internal override void SetTypeIfNecessary()
        {
            
        }
    }
}